package com.jzo2o.orders.manager.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jzo2o.orders.base.enums.OrderCancelStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersCanceled;
import com.jzo2o.orders.manager.service.IOrdersCanceledService;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单定时任务
 */
@Slf4j
@Component
public class OrderJob {
    @Resource
    private IOrdersCreateService ordersCreateService;
    @Resource
    private IOrdersCanceledService ordersCanceledService;

    /**
     * 定时取消订单
     * 1.查询订单状态为待支付，且创建时间小于当前时间减15分钟的订单
     * 2.取消订单
     */
    @XxlJob("cancelOrder")
    public void cancelOrder() {
        log.info("订单取消任务开始执行");
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getOrdersStatus, OrderStatusEnum.NO_PAY.getStatus())
                .lt(Orders::getCreateTime, System.currentTimeMillis() - 15 * 60 * 1000);
        List<Orders> list = ordersCreateService.list();
        //修改订单状态
        for (Orders orders : list) {
            orders.setOrdersStatus(OrderStatusEnum.CANCELED.getStatus());
            orders.setCancelReason("订单超时");
        }
        ordersCreateService.updateBatchById(list);
        //订单取消表
        ArrayList<OrdersCanceled> ordersCanceleds = new ArrayList<>();
        for (Orders orders : list) {
            OrdersCanceled ordersCanceled = new OrdersCanceled();
            ordersCanceled.setId(orders.getId());
            ordersCanceled.setCancellerType(OrderCancelStatusEnum.ADMIN.getStatus());
            ordersCanceled.setCancelReason("订单取消");
            ordersCanceled.setCancelTime(LocalDateTime.now());
            ordersCanceleds.add(ordersCanceled);
        }
        ordersCanceledService.saveBatch(ordersCanceleds);

    }

}
